﻿@page "/useraccounts"

@using Microsoft.EntityFrameworkCore
@using Microsoft.AspNetCore.Components.QuickGrid
@using BlazorAppAuth.Models
@using BlazorAppAuth.Data
@using BlazorAppAuth.Components.Pages.UserAccountPages
@inject IDbContextFactory<BlazorAppAuth.Data.BlazorAppAuthContext> DbFactory
@implements IAsyncDisposable
@rendermode InteractiveServer

<PageTitle>用户管理</PageTitle>

<h3>用户管理</h3>

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target  ="#createUserModal">
    新增用户
</button>

<div class="modal fade" id="createUserModal" data-bs-backdrop="static" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-xl  modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalToggleLabel2">新增用户</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <Create OnCreated="HandleCreateSuccess" />
            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="changeUserRoleModal" data-bs-backdrop="static" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-xl  modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalToggleLabel2">修改用户权限</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <InputSelect @bind-Value="currentModifyUser.Role" class="form-control">
                    @foreach (var role in UserRoles)
                    {
                        <option value="@role">@role</option>
                    }
                </InputSelect>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" @onclick="ChangeUserRole">保存</button>
            </div>
        </div>
    </div>
</div>

<QuickGrid Class="table" Items="context.UserAccount" @ref="myGrid">
    <PropertyColumn Property="useraccount => useraccount.Name" />
    <PropertyColumn Property="useraccount => useraccount.Password" />
    <PropertyColumn Property="useraccount => useraccount.Role" />

    <TemplateColumn Context="useraccount" Align=Align.Right Title="操作">
        @if (currentUserRole == "超级管理员" && useraccount.Role != "超级管理员") {
            <button class="btn btn-primary btn-sm ms-1" @onclick="() => RestPassowrd(useraccount)">重置密码</button>
            <button class="btn btn-primary btn-sm ms-1" @onclick="() => currentModifyUser = useraccount" data-bs-toggle="modal" data-bs-target="#changeUserRoleModal">修改权限</button>
        }
        <button class="btn btn-danger btn-sm ms-1"@onclick="()=> DeleteUser(useraccount)" >删除</button>
    </TemplateColumn>
</QuickGrid>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }
    private List<string> UserRoles = new List<string> { "超级管理员", "管理员", "维修工", "操作员" };

    BlazorAppAuthContext context = default!;
    private QuickGrid<Models.UserAccount> myGrid;
    string currentUserRole = "未知角色";

    private Models.UserAccount currentModifyUser = new UserAccount();

    private async Task HandleCreateSuccess()
    {
        // 处理子组件的点击事件
        // close modal
        Console.WriteLine("now in Order page");

        await js.InvokeVoidAsync("closeDialog", "createUserModal");
        await myGrid.RefreshDataAsync();


    }

    private async Task _Save(Models.UserAccount user)
    {
        var ctx = DbFactory.CreateDbContext();
        context.Attach(user!).State = EntityState.Modified;
        try
        {
            await context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        { }
    }

    private async Task DeleteUser(Models.UserAccount user)
    {

        bool confrmDel = await  js.InvokeAsync<bool>("confirm", "确定要删除吗?");
        if (confrmDel)
        {
            using var context = DbFactory.CreateDbContext();
            context.UserAccount.Remove(user!);
            await context.SaveChangesAsync();
            await myGrid.RefreshDataAsync();
        }
        
    }

    private async Task ChangeUserRole()
    {
        if (currentModifyUser != null)
        {
            await _Save(currentModifyUser);
            await js.InvokeVoidAsync("alert", "权限已经更改");
            await js.InvokeVoidAsync("closeDialog", "changeUserRoleModal");
            await myGrid.RefreshDataAsync();
        }
    }

    async Task RestPassowrd(Models.UserAccount user)
    {

        user.Password = "222";
        await _Save(user);
        await js.InvokeVoidAsync("alert", "密码已经重置");
        await myGrid.RefreshDataAsync();
    }

    protected override async void OnInitialized()
    {
        context = DbFactory.CreateDbContext();
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity is not null && user.Identity.IsAuthenticated)
        {
            currentUserRole = user.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value ?? "未知角色";
        }
    }

    public async ValueTask DisposeAsync() => await context.DisposeAsync();
}
